//package com.ccut.xunfeiSpringboot.controller;
//
//import com.ccut.xunfeiSpringboot.service.IseClientService;
//import com.fasterxml.jackson.core.JsonProcessingException;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RequestPart;
//import org.springframework.web.bind.annotation.RestController;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.util.HashMap;
//import java.util.Map;
//import java.util.concurrent.CompletionException;
//
//@RestController
//public class IseClientController {
//
//    @Autowired
//    private IseClientService iseClientService;
//
//    private final ObjectMapper objectMapper = new ObjectMapper();
//
//    @PostMapping("/evaluate")
//    public ResponseEntity<?> evaluateSpeech(
//            @RequestPart("audio") MultipartFile audioFile,
//            @RequestParam("text") String text) {
//
//        try {
//            String decodedJson = iseClientService.evaluateAudioFile(audioFile, text).join();
//
//            // 直接返回解码后的JSON字符串
//            return ResponseEntity.ok().body(decodedJson);
//
//        } catch (CompletionException e) {
//            return ResponseEntity.internalServerError().body(buildErrorResponse(
//                    "ISE_SERVICE_ERROR",
//                    e.getCause() != null ? e.getCause().getMessage() : "评测服务异常"
//            ));
//        } catch (Exception e) {
//            return ResponseEntity.badRequest().body(buildErrorResponse(
//                    "INVALID_REQUEST",
//                    e.getMessage()
//            ));
//        }
//    }
//
//    private String buildErrorResponse(String errorCode, String message) {
//        try {
//            Map<String, Object> error = new HashMap<>();
//            error.put("code", errorCode);
//            error.put("message", message);
//            error.put("success", false);
//            return objectMapper.writeValueAsString(error);
//        } catch (JsonProcessingException e) {
//            return "{\"code\":\"JSON_PARSE_ERROR\",\"message\":\"错误信息生成失败\"}";
//        }
//    }
//}


package com.ccut.xunfeiSpringboot.controller;

import com.ccut.xunfeiSpringboot.service.IseClientService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletionException;

@RestController
public class IseClientController {

    private static final Logger logger = LoggerFactory.getLogger(IseClientController.class);

    @Autowired
    private IseClientService iseClientService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/evaluate")
    public ResponseEntity<?> evaluateSpeech(
            @RequestPart("audio") MultipartFile audioFile,
            @RequestParam("text") String text) {

        logger.info("Received evaluation request | File: {} ({} bytes) | Text: {}",
                audioFile.getOriginalFilename(),
                audioFile.getSize(),
                text);

        try {
            String decodedJson = iseClientService.evaluateAudioFile(audioFile, text).join();

            logger.debug("Evaluation completed successfully | Result: {}",
                    decodedJson.length() > 100 ? decodedJson.substring(0, 100) + "..." : decodedJson);
            logger.info("Evaluation completed successfully | Result length: {} characters", decodedJson.length());

            return ResponseEntity.ok().body(decodedJson);

        } catch (CompletionException e) {
            String errorType = e.getCause() != null ? e.getCause().getClass().getSimpleName() : "Unknown";
            logger.error("Evaluation service failed | Error: {} | Message: {}",
                    errorType,
                    e.getCause() != null ? e.getCause().getMessage() : "No detail message",
                    e);

            return ResponseEntity.internalServerError().body(buildErrorResponse(
                    "ISE_SERVICE_ERROR",
                    e.getCause() != null ? e.getCause().getMessage() : "评测服务异常"
            ));
        } catch (Exception e) {
            logger.error("Invalid request error | Type: {} | Message: {}",
                    e.getClass().getSimpleName(),
                    e.getMessage(),
                    e);

            return ResponseEntity.badRequest().body(buildErrorResponse(
                    "INVALID_REQUEST",
                    e.getMessage()
            ));
        }
    }

    private String buildErrorResponse(String errorCode, String message) {
        try {
            Map<String, Object> error = new HashMap<>();
            error.put("code", errorCode);
            error.put("message", message);
            error.put("success", false);

            String jsonResponse = objectMapper.writeValueAsString(error);
            logger.warn("Generated error response | Code: {} | Message: {}", errorCode, message);

            return jsonResponse;
        } catch (JsonProcessingException e) {
            logger.error("JSON serialization failed for error response | Original error: {}", message, e);
            return "{\"code\":\"JSON_PARSE_ERROR\",\"message\":\"错误信息生成失败\"}";
        }
    }
}